<template>
	<view class="content" >
        <u-navbar :fixed="true" :shadow="true" :safeAreaInsetTop="true" :placeholder="true"
            @leftClick="back" title="实名认证">
        </u-navbar>

        <!-- 身份证验证 -->
        <view class="u-m-t-30 u-p-t-30 u-p-b-50 item">
            <view class="uni-area">
                <text class="u-font-32 font-bold">身份证验证</text>
                <view class="u-m-t-30 u-flex u-row-between">
                    <!-- 身份证正面 -->
                    <u-upload
                        @afterRead="afterRead" @delete="deletePic"
                        name="front" deletable :multiple="true" :maxCount="1"
                        width="330rpx" height="208rpx" uploadText="请上传身份证正面">
                       	<u--image v-if="identityCard.front" :src="identityCard.front" :showLoading="true" width="330rpx" height="208rpx" radius="8rpx"></u--image>
                    	<!-- <view v-else class="img u-flex u-row-center u-font-26">暂无身份证正面信息</view> -->
                    </u-upload>
					<!-- 身份证反面 -->
                    <u-upload
                        @afterRead="afterRead" @delete="deletePic"
                        name="back" deletable :multiple="true" :maxCount="1"
                        width="330rpx" height="208rpx" uploadText="请上传身份证反面">
						<u--image v-if="identityCard.back" :src="identityCard.back" :showLoading="true" width="330rpx" height="208rpx" radius="8rpx"></u--image>
						<!-- <view v-else class="img u-flex u-row-center u-font-26">暂无身份证反面信息</view> -->
                    </u-upload>
                </view>
                <uni-item-base-plus :baseData="identity" />
            </view>
        </view>

        <!-- 验证身份信息 -->
        <view class="u-m-t-30 u-p-t-30 u-p-b-50 item">
            <view class="uni-area">
                <text class="u-font-32 font-bold">验证身份信息</text>
                <view class="u-m-t-30 u-flex u-flex-col">
                    <u--image :src="identityCard.photo?identityCard.photo:'/static/faceHead.png'" 
                        width="266rpx" height="280rpx" radius="6" @tap="face">
                    </u--image>
                    <text class="u-m-t-30 u-font-28 uni-dec-color">提示:点击图片前往人脸识别！</text>
                </view>
            </view>
        </view>


        <!-- 下一步 -->
        <view class="next-box u-flex u-row-center">
            <u-button class="next" type="primary" shape="circle" text="完成" @tap="accomplish"></u-button>
        </view>
	</view>
</template>

<script>
import { pathToBase64 } from 'image-tools';
export default {
    data() {
        return {
            // 身份证正反面和采集的人脸信息
            identityCard:{ 
                front: '',
                back: '',
                photo: '',
                backVerify: false, // 默认身份证反面验证未通过
            },
            // 身份证信息
            identity:{
                line: false,
                title: '',
                rightText: '',
                list:[
                    { show:true, required:true, title:'姓名', value: '安薪乐' },
                    { show:true, required:true, title:'公民身份证号码', value: '安薪乐' },
                ]
            }
        }
    },

    onReady(){},



    onLoad(option) {
        // 获取当前用户身份证信息
        this.getUserIdcard(option.ywlx,option.rybh)
    },

    onShow(){
        this.identityCard.photo = uni.getStorageSync('auth_photo_url')
    },

    onBackPress(event){
        this.resetCache()
    },


    methods: {
        // 返回
        back(){
            // 重置缓存数据
            this.resetCache()
            uni.navigateBack()
        },


        // 当前账号身份证信息
        getUserIdcard(ywlx,ywbh){
            uni.showLoading({ title:'证件信息获取中' })
            const par = { ywlx: ywlx, ywbh: ywbh }
            this.$request('this',this.$apis.MemberAtta,par).then(res=>{
                res.map((v,i)=>{
                    if( v.attachType == 'sfzzm' || v.attachType == 'sfzfm') {
                        const attachType = v.attachType == 'sfzzm' ? 'front' : 'back'
                        // console.log('证件信息',v)
                        try {
                            // 图片格式转换
                            uni.request({
                                url: v.attachList[0].attachUrl, 
                                method: 'GET',
                                responseType: 'arraybuffer',
                                success: async res => {
                                    let toBase64Url = 'data:image/jpeg;base64,' + uni.arrayBufferToBase64(res.data)
                                    // 渲染后台返回的身份证正反面(不管照片的内容直接渲染)
                                    this.identityCard[attachType] = toBase64Url
                                    // 识别身份证
                                    this.getOCRsignature('auto',attachType,v.attachList[0].attachUrl,toBase64Url)
                                },
                                fail: err=>{
                                    uni.$u.toast('证件格式转换失败')
                                }
                            }); 
                        } catch (error) {}
                    }
                })
            })
        },
        
        // 新增图片
		afterRead(event) {
			uni.showLoading({ title:'上传中' })
			pathToBase64(event.file[0].url).then(res=>{
				this.getOCRsignature('manual',event.name,event.file[0].url,res)
			}).catch(err=>{})
		},
		// 删除图片
		deletePic(event) {},


        // 身份证识别
        getOCRsignature(type,attachType,url,ImageBase64){
            this.$request(this,this.$apis.ocrSignature,{ImageBase64:ImageBase64}).then(res=>{
                uni.showLoading({ title:'证件识别中' })
                uni.request({
                    url: 'https://ocr.tencentcloudapi.com',
                    method: 'POST',
                    data:{
                        ImageBase64: ImageBase64
                    },
                    header: {
                        'X-TC-Action': 'IDCardOCR',
                        'X-TC-Version': '2018-11-19',
                        'X-TC-Region': 'ap-beijing',
                        'X-TC-Timestamp': res.timestamp,
                        'Content-Type': 'application/json; charset=utf-8',
                        'Authorization': res.data,
                    },
                    success: e => {
                        uni.hideLoading()
                        if( e.data.Response.Error ){
                            if ( attachType == 'back' ) this.identityCard.backVerify = false
							uni.$u.toast('证件识别失败,请排查证件类型及证件是否能清晰完整')
                        }else{
							const result = e.data.Response
							if( attachType == 'front' ){
								if( result.Name ){
                                    if( type == 'manual' ) this.identityCard[attachType] = ImageBase64
									this.identity.list[0].value = result.Name
									this.identity.list[1].value = result.IdNum
									uni.setStorageSync('idCardBase64', ImageBase64)
                                    uni.setStorageSync('idCardUrlFront', url)
								}else{
									uni.$u.toast('证件类型错误,请手动上传')
								}
							}else{
								if( result.Authority ){
                                    if( type == 'manual' ) this.identityCard[attachType] = ImageBase64
                                    uni.setStorageSync('idCardUrlBack', url)
									this.identityCard.backVerify = true
								}else{
									uni.$u.toast('证件类型错误,请手动上传')
								}
							}
                        }
                    },
                    fail: e => {
                        uni.hideLoading()
                        if ( attachType == 'back' ) this.identityCard.backVerify = false
                        uni.$u.toast('证件识别失败')
                    }
                });
            }).then()
        },


        // 人脸识别
        face(){
            if( this.identity.list[0].value !='安薪乐' && this.identityCard.backVerify ){
                uni.navigateTo({ url: '/pages/common/face?type=my' })
            }else{
                uni.$u.toast('未获取到当前人员有效身份信息,请手动上传')
            }
        },


        // 完成
        accomplish(){
            this.back()
        },

        // 清空缓存
        resetCache(){
            // 重置缓存数据
            const arr = ['originalInfo','idCardBase64','idCardUrlFront','idCardUrlBack','auth_photo_url']
            arr.map((v,i)=>{
                uni.removeStorageSync(v)
            })
        }
    }
}
</script>

<style scoped lang="scss">
    .content{
        .img{
            width: 330rpx;
            height: 208rpx;
            background: #eaecec;
            border-radius: 12rpx;
        }
        .item{
            background: $uni-text-color-inverse;
            box-shadow: 0px 4px 20px rgba(0, 0, 0, 0.07);
        }
        .next-box{
            padding: 144rpx 0 70rpx;
            background: #FBFCFC;
            .next{
                width: 500rpx;
                margin: 0;
            }
        }
    }
</style>
